import Vue from 'vue'
import App from './App'
import router from "./router"
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'
import store from "./vuex/store";
import Cookies from 'js-cookie';


Vue.use(VueAxios, axios)
Vue.config.productionTip = false
Vue.use(ElementUI);

axios.defaults.withCredentials=true;//让ajax携带cookie


axios.interceptors.request.use(function (config) {
  let token = sessionStorage.getItem("token")
  // 在发送请求之前做些什么
  config.headers['token']=token;
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth){
    if(Boolean(sessionStorage.getItem("token"))){
      Cookies.set('token',sessionStorage.getItem("token"))
      next();
    }else{
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      });
    }
  }else{
    next();
  }
})

new Vue({
  el: '#app',
  //配置路由
  router,
  store,
  render: h => h(App),
  components: { App },
  template: '<App/>'
})
